#include "OgreStableHeaders.h"
#include "OgreDynLibManager.h"
#include "OgreDynLib.h"

namespace Ogre
{
	template<> DynLibManager* Singleton<DynLibManager>::ms_Singleton = 0;
	DynLibManager* DynLibManager::getSingletonPtr(void)
	{
		return ms_Singleton;
	}

	DynLibManager& DynLibManager::getSingleton(void)
	{
		assert(ms_Singleton); return (*ms_Singleton);
	}

	DynLibManager::DynLibManager()
	{
	}

	DynLib* DynLibManager::load(const String& filename)
	{
		DynLibList::iterator i = mLibList.find(filename);
		if (i != mLibList.end())
		{
			return i->second;
		}
		else
		{
			DynLib* pLib = OGRE_NEW DynLib(filename);
			pLib->load();
			mLibList[filename] = pLib;
			return pLib;
		}
	}

	void DynLibManager::unload(DynLib* lib)
	{
		DynLibList::iterator i = mLibList.find(lib->getName());
		if (i != mLibList.end())
		{
			mLibList.erase(i);
		}
		lib->unload();
		OGRE_DELETE lib;
	}

	DynLibManager::~DynLibManager()
	{
		for (DynLibList::iterator it = mLibList.begin(); it != mLibList.end(); ++it)
		{
			it->second->unload();
			OGRE_DELETE it->second;
		}

		mLibList.clear();
	}
}
